package com.jerry.gateway.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

//检查HttpServletRequest中是否有accessToken参数，若有，就进行路由，若没有，就返回401错误
public class AccessFilter extends ZuulFilter  {

    private static Logger log = LoggerFactory.getLogger(AccessFilter.class);

    //过滤器类型，决定过滤器在请求的哪个生命周期中执行
    @Override
    public String filterType() {
        //定义为pre，代表在请求被路由之前执行
        return FilterConstants.PRE_TYPE;
    }

    //过滤器的执行顺序。当请求在一个阶段中存在多个过滤器时，需要根据这个方法的返回值来依次执行
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    //判断过滤器是否需要执行
    @Override
    public boolean shouldFilter() {
        //返回值为true，代表这个过滤器对所有请求都会生效。
        return true;
    }

    //过滤器的具体逻辑
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            log.warn("access token is empty");
            ctx.setSendZuulResponse(false);    //让zuul过滤此请求，不对其进行路由
            ctx.setResponseStatusCode(401);    //设置返回的错误码
            ctx.setResponseBody("return body content");
            return null;
        }
        log.info("access token ok");
        return null;
    }
}
